package com.rzl.expense.common.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 时间工具类
 *
 * @author expense
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }
    /**
     * 获取传入月份的第一天和最后一天字符串数据yyyy-MM-dd
     *
     * @param month
     * @return
     */
    public static String[] getBeginAndEndDate(String month) {
        String[] result = new String[2];
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = dateFormat.parse(month + "-01");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);

            // 获取当前月份的第一天
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            Date firstDay = calendar.getTime();

            // 获取当前月份的最后一天
//            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
//            Date lastDay = calendar.getTime();

            //获取下个月的最后一天
            calendar.add(Calendar.MONTH, 1);
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
            Date lastDay = calendar.getTime();


            result[0] = parseDateToStr("yyyy-MM-dd", firstDay);
            result[1] = parseDateToStr("yyyy-MM-dd", lastDay);
        } catch (Exception e) {
            e.printStackTrace();

        }
        return result;
    }

    public static String[] getBeginAndEndDate1(String month) {
        String[] result = new String[2];
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = dateFormat.parse(month + "-01");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);

            // 获取上月的最后一天

            calendar.add(Calendar.MONTH, -1);
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            Date firstDay = calendar.getTime();


            // 获取当前月份的第一天
            calendar.add(Calendar.MONTH, 1);
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
            Date lastDay = calendar.getTime();


            result[0] = parseDateToStr("yyyy-MM-dd", firstDay);
            result[1] = parseDateToStr("yyyy-MM-dd", lastDay);
        } catch (Exception e) {
            e.printStackTrace();

        }
        return result;
    }

    /**
     *
     * 描述:获取下一个月的第一天.
     *
     * @return
     */
    public static String getPerFirstDayOfMonth() {
        SimpleDateFormat dft = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        return dft.format(calendar.getTime());
    }

    /**
     *
     * 描述:获取上个月的最后一天.
     *
     * @return
     */
    public static String getLastMaxMonthDate() {
        SimpleDateFormat dft = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        return dft.format(calendar.getTime());
    }


    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor) {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor) {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 得到年月
     *
     * @param minDate 开始时间
     * @param maxDate 结束时间
     * @return {@link List}<{@link String}>
     */
    public static List<String> getMonthBetween(Date minDate, Date maxDate) {
        ArrayList<String> result = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(minDate);
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        max.setTime(maxDate);
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

        Calendar curr = min;
        while (curr.before(max)) {
            result.add(sdf.format(curr.getTime()));
            curr.add(Calendar.MONTH, 1);
        }
        return result;
    }

    /**
     * 字符串转日期 【"2024-08"】
     */
    public Date convert(String s) {
        Date date = null;
        //实现将字符串转成⽇期类型
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        try {
            date = dateFormat.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static String getTbDate(String currentDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        String monthFormat;
        try {
            date = sdf.parse(currentDate + "-" + "01");
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.YEAR, -1);
        int month = c.get(Calendar.MONTH) + 1;
        if (month <= 9) {
            monthFormat = "0" + month;
        } else {
            monthFormat = String.valueOf(month);
        }
        String tbDate = c.get(Calendar.YEAR) + "-"
                + monthFormat;
        return tbDate;
    }


    //获取本年1月到上月
    public static List<String> getYearMonths(String dateStr) {
//        List<String> list = new ArrayList<>();
//        try {
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            Date date = sdf.parse(dateStr + "-01");
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(date); // 设置为当前时间
//
//            for (int month = 1; month < calendar.get(Calendar.MONTH) + 1; month++) {
//                list.add(calendar.get(Calendar.YEAR) + "-" + String.format("%02d", month));
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//
//        }
//
//        return list;

        List<String> list = new ArrayList<>();
        list.add("2024-01");
        list.add("2024-02");
        list.add("2024-03");
        list.add("2024-04");
        list.add("2024-05");
        list.add("2024-06");
        list.add("2024-07");
        list.add("2024-08");
        list.add("2024-09");
        list.add("2024-10");
        list.add("2024-11");
        list.add("2024-12");
        list.add("2025-01");
//        list.add("2025-02");
        return list;
    }

    public static List<String> getMonths(String startMonth,String endMonth){
        List<String> list=new ArrayList<>();
        DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM");
        YearMonth start=YearMonth.parse(startMonth,formatter);
        YearMonth end=YearMonth.parse(endMonth,formatter);
        YearMonth curent=start;
        while (!curent.isAfter(end)){
            list.add(curent.format(formatter));
            curent=curent.plusMonths(1);
        }
        return list;
    }


    public static String formatDate(String currentDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;

        try {
            date = sdf.parse(currentDate + "-" + "01");

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return parseDateToStr("yyyy-MM-dd", date);
    }

    //获取前一年
    public static List<String> getPreviousMonth(String date) {
//        String date1 = "2019-06-13";
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date2 = LocalDate.parse(date, fmt);
        List<String> list = new ArrayList<>();
//        LocalDate now = LocalDate.now();
        // 获取当前年份和月份
        YearMonth currentYearMonth = YearMonth.from(date2);
        // 获取前一年同一月份
        YearMonth oneYearAgo = currentYearMonth.minusYears(1);
        // 循环遍历前一年的所有月份
        for (int month = 0; month < 12; month++) {
            YearMonth yearMonth = oneYearAgo.plusMonths(month);
            list.add(yearMonth.getYear() + "-" + String.format("%02d", yearMonth.getMonthValue()));
        }
        return list;
    }

    public static void main(String[] args) {
        System.out.println(getMonths("2024-01","2024-12"));
    }
}
